﻿using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Util.Common;
using Core.Middleware.WebSockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;

namespace Core.Web
{
    public static class ApplicationLifetime
    {
        /// <summary>
        /// 注册系统退出事件
        /// </summary>
        /// <param name="lifetime"></param>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IHostApplicationLifetime RegisterApplicationLifetime(this IHostApplicationLifetime lifetime , IApplicationBuilder app)
        {
            lifetime.ApplicationStopped.Register(() =>
            {
                Console.WriteLine("系统退出");
                CoreStartupHelper.IsApplicationStopping = false;
            });

            lifetime.ApplicationStopping.Register(() =>
            {

                Console.WriteLine("系统准备退出...");
                CoreStartupHelper.IsApplicationStopping = true;

                try
                {
                    foreach (var item in WebSocketApplication.ClientsPool)
                    {
                        item.Key.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.Empty, "服务重启", new System.Threading.CancellationToken());
                    }
                }
                catch
                {
                }

                TimerJob timer = new TimerJob();
                timer.Stop();

                app.UninstallWebSocketServiceClient();


            });

            return lifetime;
        }
    }
}
